<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\File;
use think\Session;

/**
 * 套餐
 *
 * @icon fa fa-circle-o
 */
class Setmeal extends Backend
{

    /**
     * Setmeal模型对象
     * @var \app\admin\model\Setmeal
     */
    protected $model = null;
    private $cacheName = 'setmealCache';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Setmeal;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'name', 'price', 'status', 'image', 'update_time']);
                $row->visible(['category']);
                $row->getRelation('category')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        // dump($params);
        // exit;
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        // 第一步：检查文件是否存在
        $imagePath = ROOT_PATH . 'public' . str_replace('/', DS, $params['image']);
        if (!is_file($imagePath)) {
            // 记录日志（可选，但推荐）
            \think\Log::write("图片不存在，路径：{$imagePath}", 'error');
            return json([
                'code' => 0,
                'msg'  => '图片不存在，请重新上传'
            ]);
        }

        // 套餐数据
        $image = new File($imagePath);
        $data = [
            'name' => $params['name'] ?? '',
            'category' => $params['category_id'] ?? '',
            'price' => $params['price'] ?? '',
            'image' => $image,
            'description' => $params['description'] ?? '',
            'dish_list' => $params['dish_list'] ?? null,
        ];

        // 验证数据合法性
        $validate = validate('Setmeal');
        if (!$validate->scene('add')->check($data)) {
            $this->error($validate->getError());
        }

        // 验证套餐名称是否重复
        $setmeal = $this->model
            ->where('name', $params['name'])
            ->find();

        if ($setmeal) {
            $this->error('套餐名称重复，请调整');
        }

        $adminId = $this->auth->__get('id');
        $params['create_user'] = $adminId;
        $params['update_user'] = $adminId;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            // 保存套餐主数据
            $result = $this->model->allowField(true)->save($params);
            $setmealId = $this->model->id; // 获取新套餐ID

            // 4. 处理中间表数据（手动构建）
            $middleData = []; // 存储中间表要插入的数据
            if (isset($params['dish_list']) && is_array($params['dish_list'])) {
                foreach ($params['dish_list'] as $dish) {
                    // 提取字段（严格匹配中间表字段名）
                    $dishId = $dish['id'];          // 菜品ID（dish_id）
                    $copies = $dish['copies'];       // 额外字段（份数）
                    $dishName = $dish['name'];  // 冗余字段（菜品名称）
                    $dishPrice = $dish['price']; // 冗余字段（菜品单价）

                    // 验证字段有效性（避免脏数据）
                    if (empty($dishId) || !is_numeric($copies) || empty($dishName) || !is_numeric($dishPrice)) {
                        throw new \Exception("菜品参数无效：" . json_encode($dish));
                    }

                    // 构建中间表数据行（字段名必须与中间表一致）
                    $middleData[] = [
                        'setmeal_id' => $setmealId,  // 套餐ID（外键）
                        'dish_id' => $dishId,        // 菜品ID（外键）
                        'copies' => $copies,         // 额外字段（份数）
                        'name' => $dishName,    // 冗余字段（菜品名称）
                        'price' => $dishPrice,  // 冗余字段（菜品单价）
                    ];
                }

                // 5. 批量插入中间表（高效！）
                if (!empty($middleData)) {
                    Db::name('setmeal_dish')->insertAll($middleData);
                }
            }
            $cacheKey = $this->cacheName . $params['category_id'];
            Cache::rm($cacheKey);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            // 获取菜品数据
            $setmeal = $this->model->alias('s')
                ->join('setmeal_dish sd', 's.id = sd.setmeal_id') // 中间表
                ->join('dish d', 'd.id = sd.dish_id')
                ->where('s.id', $ids)
                ->field('d.id,sd.name, sd.price , sd.copies') // 包含中间表 copies
                ->select();

            $this->view->assign('setmeal', $setmeal);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        // 套餐数据
        // 第一步：检查文件是否存在
        $imagePath = ROOT_PATH . 'public' . str_replace('/', DS, $params['image']);
        if (!is_file($imagePath)) {
            // 记录日志（可选，但推荐）
            \think\Log::write("图片不存在，路径：{$imagePath}", 'error');
            return json([
                'code' => 0,
                'msg'  => '图片不存在，请重新上传'
            ]);
        }

        // 套餐数据
        $image = new File($imagePath);
        $data = [
            'name' => $params['name'] ?? '',
            'category' => $params['category_id'] ?? '',
            'price' => $params['price'] ?? '',
            'image' => $image,
            'description' => $params['description'] ?? '',
            'dish_list' => $params['dish_list'] ?? null,
        ];

        // 验证数据合法性
        $validate = validate('Setmeal');
        if (!$validate->scene('edit')->check($data)) {
            $this->error($validate->getError());
        }

        // 验证套餐名称是否重复
        $setmeal = $this->model
            ->where('id', '<>', $ids)
            ->where('name', $params['name'])
            ->find();

        if ($setmeal) {
            $this->error('套餐名称重复，请调整');
        }

        $adminId = $this->auth->__get('id');
        $params['update_user'] = $adminId;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::name('setmeal_dish')->where('setmeal_id', $ids)->delete(); // 删除旧关联
            // 4. 处理中间表数据（手动构建）
            $middleData = []; // 存储中间表要插入的数据
            if (isset($params['dish_list']) && is_array($params['dish_list'])) {
                foreach ($params['dish_list'] as $dish) {
                    // 提取字段（严格匹配中间表字段名）
                    $dishId = $dish['id'];          // 菜品ID（dish_id）
                    $copies = $dish['copies'];       // 额外字段（份数）
                    $dishName = $dish['name'];  // 冗余字段（菜品名称）
                    $dishPrice = $dish['price']; // 冗余字段（菜品单价）

                    // 验证字段有效性（避免脏数据）
                    if (empty($dishId) || !is_numeric($copies) || empty($dishName) || !is_numeric($dishPrice)) {
                        throw new \Exception("菜品参数无效：" . json_encode($dish));
                    }

                    // 构建中间表数据行（字段名必须与中间表一致）
                    $middleData[] = [
                        'setmeal_id' => $ids,  // 套餐ID（外键）
                        'dish_id' => $dishId,        // 菜品ID（外键）
                        'copies' => $copies,         // 额外字段（份数）
                        'name' => $dishName,    // 冗余字段（菜品名称）
                        'price' => $dishPrice,  // 冗余字段（菜品单价）
                    ];
                }

                // 5. 批量插入中间表（高效！）
                if (!empty($middleData)) {
                    Db::name('setmeal_dish')->insertAll($middleData);
                }
            }
            $cacheKey = $this->cacheName . $params['category_id'];
            Cache::rm($cacheKey);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                // 起售状态下不可删除
                if ($item->status == 1) {
                    throw new Exception('在售状态下，不可删除套餐');
                }
                // 删除套餐关联菜品
                Db::name('setmeal_dish')->where('setmeal_id', $item->id)->delete();
                $count += $item->delete();
            }
            Cache::clear($this->cacheName);
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
